﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Model;
using System.Net;
using StockFinder.Network;

namespace StockFinder.GoogleFinance
{
    public class GoogleFinanceOnlineStockPriceHistoryExtractor : IHistoricDailyPricesExtractor
    {
        const string BASE_URL = "http://www.google.co.uk/finance/historical?q={0}&startdate={1}&enddate={2}&output=csv";
        //DateFormat: Nov+12%2C+2010


        public List<DailyPrice> GetHistoricPrices(Symbol symbol, DateTime fromDate, DateTime toDate)
        {
            List<DailyPrice> prices = null;            

            string startDate = string.Format("{0}%{1}", fromDate.ToString("MMM+dd"), fromDate.ToString("2C+yyyy"));
            string endDate = string.Format("{0}%{1}", toDate.ToString("MMM+dd"), toDate.ToString("2C+yyyy"));

            var pricesUrl = string.Format(BASE_URL, FormattedForExchange(symbol), startDate, endDate);

            bool success = false;
            string pageSource = null;

            using (var webClient = new ProxiedWebClient())
            {
                try
                {
                    pageSource = webClient.DownloadString(pricesUrl);

                    success = true;

                    var lines = pageSource.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries).Skip(1);

                    prices = new List<DailyPrice>();

                    foreach (var line in lines)
                    {
                        var cells = line.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                        try
                        {
                            prices.Add(new DailyPrice()
                            {
                                PriceDate = DateTime.Parse(cells[0]),
                                Open = decimal.Parse(cells[1]),
                                High = decimal.Parse(cells[2]),
                                Low = decimal.Parse(cells[3]),
                                Close = decimal.Parse(cells[4]),
                                Volume = decimal.Parse(cells[5]),
                                AdjustedClose = decimal.Parse(cells[4])
                            });
                        }
                        catch (Exception exception)
                        {
                            
                        }                        
                    }
                }
                catch (Exception exception)
                {
                    //_Log.ErrorFormat("Error reading webpage source for '{0}'. {1}", symbolName, exception.ToString());
                }
            }

            return prices;
        }

        private string FormattedForExchange(Symbol symbol)
        {
            var formattedSymbolName = symbol.Name;

            switch (symbol.Exchange)
            {
                case StockFinder.Model.Enumerations.Exchange.None:
                    break;
                case StockFinder.Model.Enumerations.Exchange.NASDAQ:
                    formattedSymbolName = string.Format("NASDAQ%3A{0}", symbol.Name);
                    break;
                case StockFinder.Model.Enumerations.Exchange.NYSE:
                    formattedSymbolName = string.Format("NYSE%3A{0}", symbol.Name);
                    break;
                case StockFinder.Model.Enumerations.Exchange.LONDON:
                    formattedSymbolName = string.Format("LON%3A{0}", symbol.Name);
                    break;
                case StockFinder.Model.Enumerations.Exchange.AMEX:
                    formattedSymbolName = string.Format("AMEX%3A{0}", symbol.Name);
                    break;
                default:
                    break;
            }

            return formattedSymbolName;
        }
    }
}
